<?php

namespace app\api\service;

use app\admin\model\PoliteArticle;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class Article
{
    public static function getList(string $keyword,$type,$pageNum,$pageSize): array
    {
        $map=[];
        if($keyword){
            $map[]=['title','like','%'.$keyword.'%'];
        }
        $map[]=['type','=',$type];
        $model=new PoliteArticle();
        $list=$model->where($map)->order('order asc')->field('id,create_time,title,cover_photo')->page($pageNum,$pageSize)->select();
        return $list->isEmpty()?[]:$list->toArray();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function getDetail(int $id){
        $map=[['id','=',$id]];
        $model=new PoliteArticle();
        $row=$model->where($map)->find();
        if(!$row){
            throw new Exception('数据不存在');
        }
        $row=$row->toArray();
        $row['content']=self::getHtml($row['content']);
        return $row;
    }

    public static function getHtml($data): string
    {
        return htmlspecialchars_decode(stripslashes($data));
    }
}